package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.entity.WorkflowDefinition;
import com.micro.ai.template.entity.WorkflowExecution;
import com.micro.ai.template.service.WorkflowService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.Map;

/**
 * 工作流Controller
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/workflows")
@RequiredArgsConstructor
@Tag(name = "工作流管理", description = "工作流相关接口")
public class WorkflowController {

    private final WorkflowService workflowService;

    @PostMapping
    @PreAuthorize("hasAuthority('workflow:create')")
    @Operation(summary = "创建工作流", description = "创建新的工作流定义")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功",
            content = @Content(schema = @Schema(implementation = WorkflowDefinition.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<WorkflowDefinition> createWorkflow(
            @Valid @RequestBody WorkflowDefinition workflow) {
        log.info("创建工作流请求, name: {}", workflow.getWorkflowName());
        return workflowService.createWorkflow(workflow);
    }

    @PutMapping("/{workflowId}")
    @PreAuthorize("hasAuthority('workflow:update')")
    @Operation(summary = "更新工作流", description = "更新工作流定义")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功",
            content = @Content(schema = @Schema(implementation = WorkflowDefinition.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "工作流不存在")
    })
    public ApiResponse<WorkflowDefinition> updateWorkflow(
            @Parameter(description = "工作流ID") @PathVariable String workflowId,
            @Valid @RequestBody WorkflowDefinition workflow) {
        log.info("更新工作流请求, workflowId: {}", workflowId);
        return workflowService.updateWorkflow(workflowId, workflow);
    }

    @DeleteMapping("/{workflowId}")
    @PreAuthorize("hasAuthority('workflow:delete')")
    @Operation(summary = "删除工作流", description = "删除工作流定义")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "工作流不存在")
    })
    public ApiResponse<Void> deleteWorkflow(
            @Parameter(description = "工作流ID") @PathVariable String workflowId) {
        log.info("删除工作流请求, workflowId: {}", workflowId);
        return workflowService.deleteWorkflow(workflowId);
    }

    @GetMapping("/{workflowId}")
    @PreAuthorize("hasAuthority('workflow:query')")
    @Operation(summary = "查询工作流详情", description = "根据ID查询工作流详情")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = WorkflowDefinition.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "工作流不存在")
    })
    public ApiResponse<WorkflowDefinition> getWorkflowById(
            @Parameter(description = "工作流ID") @PathVariable String workflowId) {
        return workflowService.getWorkflowById(workflowId);
    }

    @GetMapping
    @PreAuthorize("hasAuthority('workflow:query')")
    @Operation(summary = "查询工作流列表", description = "分页查询工作流列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Page<WorkflowDefinition>> listWorkflows(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "查询参数") @RequestParam(required = false) Map<String, Object> params) {
        return workflowService.listWorkflows(pageNum, pageSize, params);
    }

    @PostMapping("/{workflowId}/execute")
    @PreAuthorize("hasAuthority('workflow:execute')")
    @Operation(summary = "执行工作流", description = "执行指定的工作流")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "执行成功",
            content = @Content(schema = @Schema(implementation = WorkflowExecution.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "工作流不存在")
    })
    public ApiResponse<WorkflowExecution> executeWorkflow(
            @Parameter(description = "工作流ID") @PathVariable String workflowId,
            @RequestBody Map<String, Object> inputData) {
        log.info("执行工作流请求, workflowId: {}", workflowId);
        return workflowService.executeWorkflow(workflowId, inputData);
    }

    @PostMapping("/executions/{executionId}/cancel")
    @PreAuthorize("hasAuthority('workflow:execute')")
    @Operation(summary = "取消工作流执行", description = "取消正在执行的工作流")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "取消成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "工作流状态不允许取消"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "执行记录不存在")
    })
    public ApiResponse<Void> cancelExecution(
            @Parameter(description = "执行ID") @PathVariable String executionId) {
        log.info("取消工作流执行请求, executionId: {}", executionId);
        return workflowService.cancelExecution(executionId);
    }

    @GetMapping("/executions/{executionId}")
    @PreAuthorize("hasAuthority('workflow:query')")
    @Operation(summary = "查询执行详情", description = "查询工作流执行详情")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = WorkflowExecution.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "执行记录不存在")
    })
    public ApiResponse<WorkflowExecution> getExecutionById(
            @Parameter(description = "执行ID") @PathVariable String executionId) {
        return workflowService.getExecutionById(executionId);
    }

    @GetMapping("/{workflowId}/executions")
    @PreAuthorize("hasAuthority('workflow:query')")
    @Operation(summary = "查询执行历史", description = "查询工作流的执行历史")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "工作流不存在")
    })
    public ApiResponse<Page<WorkflowExecution>> listExecutionHistory(
            @Parameter(description = "工作流ID") @PathVariable String workflowId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        return workflowService.listExecutionHistory(workflowId, pageNum, pageSize);
    }
}

